<?php
namespace app\admin\controller;

use app\common\model\Menu as MenuModel;
/**
 * 菜单控制器
 */
class Menu extends Admin 
{
	/**
	 * 菜单首页
	 */
	public function index(){
		$list = MenuModel::getList();
		
        $this->assign('list',$list);
        return $this->fetch();
	}

	/**
	 * 新增菜单
	 * @param integer $pid 父ID
	 */
	public function add($pid = 0){
		if($this->request->isPost()){
			$data = $this->request->post();
            // 验证
            $result = $this->validate($data, [
                'title|标题' => 'require'
            ]);
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            if($query = MenuModel::create($data)){
                $this->success('新增成功');
            }else{
                $this->error('新增失败');
            }
		}else{
			$plist = MenuModel::getList();

			$this->assign('title', '新增菜单');
			$this->assign('plist', $plist);
			$this->assign('pid', $pid);
			$this->assign('info', null);

			return $this->fetch('edit');
		}
	}

	/**
	 * 编辑菜单
	 * @param  integer $id 菜单ID
	 * @return mixed
	 */
	public function edit($id = 0){
		if($this->request->isPost()){
			$data = $this->request->post();
            // 验证
            $result = $this->validate($data, [
                'title|标题' => 'require'
            ]);
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            if($query = MenuModel::update($data)){
                $this->success('编辑成功');
            }else{
                $this->error('编辑失败');
            }
		}else{
			empty($id) && $this->error('参数错误');

			$info = MenuModel::where('id',$id)->find();
			$plist = MenuModel::getList();

			$this->assign('title', '编辑菜单');
			$this->assign('plist', $plist);
			$this->assign('info', $info);
			$this->assign('pid', $info['pid']);

			return $this->fetch();
		}
	}

	/**
	 * 删除菜单
	 * @param  integer $id 菜单ID
	 * @return mixed
	 */
	public function del($id = 0){
		empty($id) && $this->error('参数错误');

		if(is_array($id)){
            $map[] = ['id','in',$id];
        }elseif(is_numeric($id)){
            $map[] = ['id','=',$id];
        }

        if($query = MenuModel::where($map)->delete()){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
	}

	/**
	 * 更新状态
	 * @return mixed
	 */
	public function update(){
		$data = $this->request->param();

		if(empty($data)){
			$this->error('参数错误');
		}

		if($query = MenuModel::update($data)){
            $this->success('更新成功');
        }else{
            $this->error('更新失败');
        }
	}	
}